//
//  MainViewController.m
//  moon
//
//  Created by beyself on 16/6/5.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "MainViewController.h"
#import "CreateViewController.h"
#import "CustomTableView.h"

@interface MainViewController ()<UIScrollViewDelegate>

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"班级圈";
    
    _bottomLayer = [[CALayer alloc] init];
    _bottomLayer.frame = CGRectMake(0, 28, SCREEN_WIDTH/4, 4);
    _bottomLayer.backgroundColor = BLUE.CGColor;
    
    _mSelectClass = [[NSMutableArray alloc] init];
    NSArray* classes = APPDELEGATE.mMemberInfo[@"classes"];
    for(NSDictionary* dic in classes)
    {
        [_mSelectClass addObject:[dic[@"id"] description]];
    }
    
    UIScrollView* scrollView = [[UIScrollView alloc] init];
    scrollView.tag = 20000;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    scrollView.frame = CGRectMake(0, 32, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 32);
    scrollView.contentSize = CGSizeMake(4*SCREEN_WIDTH, 0);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    
    int width = SCREEN_WIDTH/4;
    for(int i = 0; i < 4; i++)
    {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(width*i, 0, width, 32);
        button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
        button.tag = 2000 + i;
        if(i == 0) [button setTitle:@"动态" forState:UIControlStateNormal];
        if(i == 1) [button setTitle:@"作业" forState:UIControlStateNormal];
        if(i == 2) [button setTitle:@"通知" forState:UIControlStateNormal];
        if(i == 3) [button setTitle:@"考勤" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
        [button setTitleColor:BLACK forState:UIControlStateNormal];
        [button setTitleColor:BLUE forState:UIControlStateSelected];
        [self.view addSubview:button];
        
        if(APPDELEGATE.newType == i || (APPDELEGATE.newType == -1 && i == 0))
        {
            APPDELEGATE.newType = -1;
            button.selected = YES;
            [button.layer addSublayer:_bottomLayer];
            _mTabBtn = button;
        }
        
        UILabel* label = [[UILabel alloc] init];
        if(i == -1) label.frame = CGRectMake(width/2 + 20, 5, 16, 16);
        else label.frame = CGRectMake(width/2 + 10, 5, 16, 16);
        label.textColor = WHITE;
        label.backgroundColor = RED;
        label.font = FONT_10;
        label.hidden = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 8;
        label.layer.masksToBounds = YES;
        label.tag = 101;
        [button addSubview:label];
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 31.5, width, .5);
        layer.backgroundColor = LINE.CGColor;
        [button.layer addSublayer:layer];
        
        CustomTableView* subview = [[CustomTableView alloc] init:i];
        subview.tag = 30000 + i;
        subview.frame = CGRectMake(i*SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 32);
        [scrollView addSubview:subview];
    }
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -5;
    self.navigationItem.leftBarButtonItems = @[negativeSpacer,
                                               [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_filter"]
                                                                                style:UIBarButtonItemStylePlain
                                                                               target:self
                                                                               action:@selector(showClassChoose)]];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_identity"]
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(showDetail)];
    
    [scrollView setContentOffset:CGPointMake((_mTabBtn.tag - 2000)*SCREEN_WIDTH, 0) animated:NO];
    CustomTableView* subview = (CustomTableView*)[self.view viewWithTag:30000 + _mTabBtn.tag - 2000];
    [subview sendDataHttpPost];
}

- (void) showDetail
{
    CreateViewController* subview = [[CreateViewController alloc] init];
    subview.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:subview animated:YES];
}

- (void) setRed:(NSDictionary*)data
{
    [[self.view viewWithTag:2000] viewWithTag:101].hidden = YES;
    [[self.view viewWithTag:2001] viewWithTag:101].hidden = YES;
    [[self.view viewWithTag:2002] viewWithTag:101].hidden = YES;
    [[self.view viewWithTag:2003] viewWithTag:101].hidden = YES;
    
    BOOL redDot = false;
    int number = 0;
    if(![NSStringFromClass(data.class) containsString:@"NSArray"])
    {
        NSArray* keys = [data allKeys];
        for(NSString* key in keys)
        {
            int num = [data[key][@"number"] intValue];
            if([key isEqualToString:@"1"] && num > 0)
            {
                [[self.view viewWithTag:2001] viewWithTag:101].hidden = NO;
                ((UILabel*)[[self.view viewWithTag:2001] viewWithTag:101]).text = [NSString stringWithFormat:@"%d",num];
                number += num;
                
                [APPDELEGATE setTabInit:YES tab:1];
            }
            else if([key isEqualToString:@"2"] && num > 0)
            {
                [[self.view viewWithTag:2002] viewWithTag:101].hidden = NO;
                ((UILabel*)[[self.view viewWithTag:2002] viewWithTag:101]).text = [NSString stringWithFormat:@"%d",num];
                number += num;
                
                [APPDELEGATE setTabInit:YES tab:2];
            }
            else if([key isEqualToString:@"4"])
            {
                [[self.view viewWithTag:2000] viewWithTag:101].hidden = NO;
                if(num > 0)
                {
                    number += num;
                    ((UILabel*)[[self.view viewWithTag:2000] viewWithTag:101]).text = [NSString stringWithFormat:@"%d",num];
                }
                else
                {
                    redDot = YES;
                    ((UILabel*)[[self.view viewWithTag:2000] viewWithTag:101]).text = @"";
                }
                
                [APPDELEGATE setTabInit:YES tab:0];
            }
            else if(num > 0)
            {
                [[self.view viewWithTag:2003] viewWithTag:101].hidden = NO;
                ((UILabel*)[[self.view viewWithTag:2003] viewWithTag:101]).text = [NSString stringWithFormat:@"%d",num];
                number += num;
                
                [APPDELEGATE setTabInit:YES tab:3];
            }
        }
    }
    
    if(number > 0)
    {
        APPDELEGATE.newMessage = number;
        [self.tabBarItem setBadgeValue:[NSString stringWithFormat:@"%d",number]];
    }
    else
    {
        APPDELEGATE.newMessage = 0;
        if(redDot)
        {
            [self.tabBarItem setBadgeValue:@" "];
        }
        else
        {
            [self.tabBarItem setBadgeValue:nil];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView.tag == 20000)
    {
        int index = scrollView.contentOffset.x/SCREEN_WIDTH;
        [self buttonClick:[self.view viewWithTag:2000 + index]];
    }
}

- (void) viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [APPDELEGATE setChatUnread];
    
    CustomTableView* subview = (CustomTableView*)[self.view viewWithTag:30000 + _mTabBtn.tag - 2000];
    [subview sendDataHttpPost];
}

- (void) refreshUIData
{
    [self buttonClick:_mTabBtn];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void) buttonClick:(UIButton*)btn
{
    if(!_mTabBtn) return;
    
    _mTabBtn.selected = NO;
    _mTabBtn = btn;
    [_bottomLayer removeFromSuperlayer];
    _mTabBtn.selected = YES;
    [_mTabBtn.layer addSublayer:_bottomLayer];

    UIScrollView* scrollview = (UIScrollView*)[self.view viewWithTag:20000];
    [scrollview setContentOffset:CGPointMake(SCREEN_WIDTH*(btn.tag - 2000), 0) animated:NO];
    
    CustomTableView* subview = (CustomTableView*)[self.view viewWithTag:30000 + _mTabBtn.tag - 2000];
    [subview sendDataHttpPost];
}

- (void) showClassChoose
{
    _inputView = [[UIControl alloc] init];
    _inputView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + 64);
    _inputView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.3];
    [_inputView addTarget:self action:@selector(removeSelf) forControlEvents:UIControlEventTouchUpInside];
    [APPDELEGATE.window addSubview:_inputView];
    
    NSArray* array = APPDELEGATE.mMemberInfo[@"classes"];
    UIView* subview = [[UIView alloc] init];
    subview.frame = CGRectMake(0, 0, SCREEN_WIDTH*2/3, (array.count + 1)*44);
    subview.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    [_inputView addSubview:subview];
    
    int count = array.count;
    for(int i = 0; i < count; i++)
    {
        NSDictionary* item = array[i];
        
        NSString* className = item[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = item[@"class_name"];
        
        UIButton* button  = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 4000 + i;
        button.frame = CGRectMake(0, 44*i, SCREEN_WIDTH*2/3, 44);
        button.titleLabel.font = FONT_15;
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:BLACK forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(classClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:className forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"check_win"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"check_win_focus"] forState:UIControlStateSelected];
        [subview addSubview:button];
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 43.5, SCREEN_WIDTH*2/3, .5);
        layer.backgroundColor = LINE.CGColor;
        [button.layer addSublayer:layer];
        
        if([self isClassChoose:[item[@"id"] description] type:0])
        {
            button.selected = YES;
        }
    }
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 44*count, SCREEN_WIDTH*2/3, 44);
    button.titleLabel.font = FONT_15;
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
    [button addTarget:self action:@selector(confirmClass) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[Utils imageFromColor:BLUE] forState:UIControlStateNormal];
    [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
    [subview addSubview:button];
}

- (void) confirmClass
{
    if(_mSelectClass.count == 0)
    {
        [self showAllTextDialog:@"请选择至少一个班级"];
    }
    else
    {
        [self removeSelf];
        
        [APPDELEGATE setTabInit:YES tab:0];
        [APPDELEGATE setTabInit:YES tab:1];
        [APPDELEGATE setTabInit:YES tab:2];
        [APPDELEGATE setTabInit:YES tab:3];
        
        CustomTableView* subview = (CustomTableView*)[self.view viewWithTag:30000 + _mTabBtn.tag - 2000];
        [subview sendDataHttpPost];
    }
}

- (void) classClick:(UIButton*)btn
{
    int index = (int)(btn.tag - 4000);
    NSDictionary* item = APPDELEGATE.mMemberInfo[@"classes"][index];
    
    if([self isClassChoose:[item[@"id"] description] type:1]) btn.selected = NO;
    else
    {
        [_mSelectClass addObject:[item[@"id"] description]];
        btn.selected = YES;
    }
}

- (BOOL) isClassChoose:(NSString*)classId type:(int)type
{
    for(int i = 0; i < _mSelectClass.count; i++)
    {
        if([_mSelectClass[i] isEqualToString:classId])
        {
            if(type) [_mSelectClass removeObjectAtIndex:i];
            return YES;
        }
    }
    
    return NO;
}

- (void) removeSelf
{
    [_inputView removeFromSuperview];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    if(_mTabBtn.tag == 2000)
    {
        [(CustomTableView*)[self.view viewWithTag:30000] keyboardChange:keyboardF.size.height];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
